import wxValidate from 'wechat-validate'

const app = getApp()

Page({
  data: {
    countDownVisible: true,
    mobile: '17358184955',
    code: '123456',
  },
  behaviors: [wxValidate],
  // 校验规则对象
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' },
    ],
    code: [
      { required: true, message: '请填写短信验证码!' },
      {
        pattern: /^\d{6}$/,
        message: '短信验证码必须6位数字',
      },
    ],
  }, // 这里的规则的键名必须是rules

  countDownChange(ev) {
    // console.log(ev.detail)
    this.setData({
      timeData: ev.detail,
      // 60
      // countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  finish() {
    this.setData({
      countDownVisible: true,
    })
  },
  async getSMSCode() {
    // validate方法是插件提供的
    const { valid, message } = this.validate('mobile')
    if (!valid) return wx.utils.toast(message)
    const { code } = await wx.http.get('/code', { mobile: this.data.mobile })
    if (code !== 10000) return wx.utils.toast('发送失败')
    this.setData({
      countDownVisible: false,
    })
  },

  async login() {
    // 校验表单
    // 不要传任何参数就会校验整个表单
    if (!this.validate()) return

    const { code, data } = await wx.http.post('/login', {
      mobile: this.data.mobile,
      code: this.data.code,
    })
    if (code !== 10000) return wx.utils.toast('登录失败，稍后重试')
    // 把token存储起来

    app.setToken('token', data.token)
    app.setToken('refreshToken', data.refreshToken)

    // 页面跳转
    wx.switchTab({
      url: '/pages/my/index',
    })
  },
})
